package com.xhh.nphm.gaoxin.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xhh.nphm.common.core.controller.BaseController;
import com.xhh.nphm.common.core.domain.AjaxResult;
import com.xhh.nphm.common.core.domain.entity.SysUser;
import com.xhh.nphm.common.core.page.TableDataInfo;
import com.xhh.nphm.common.utils.ShiroUtils;
import com.xhh.nphm.gaoxin.entity.GxqTwfJudgeEty;
import com.xhh.nphm.gaoxin.entity.GxqTwfSendBackEty;
import com.xhh.nphm.gaoxin.entity.GxqTworkFormBaseEty;
import com.xhh.nphm.gaoxin.entity.GxqTworkFormLogEty;
import com.xhh.nphm.gaoxin.service.GxqITwfJudgeService;
import com.xhh.nphm.gaoxin.service.GxqITworkFormLogService;
import com.xhh.nphm.gaoxin.service.GxqIWfSendBackService;
import com.xhh.nphm.gaoxin.service.GxqIWorkFormBaseService;
import com.xhh.nphm.system.mapper.CommonDao;
import com.xhh.nphm.system.service.*;
import com.xhh.nphm.web.controller.common.CommonController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/gaoxin/system/mTelWF/forShow")
public class GxqMTelWFforShowController extends BaseController {
    private String prefix = "system/gaoxin/mTelWF/forShow";
    @Autowired
    private CommonDao commonDao;
    @Autowired
    private ISmsNoteService smsNoteService;
    @Autowired
    private CommonController commonController;
    @Autowired
    private GxqITwfJudgeService gxqITwfJudgeService;
    @Autowired
    private GxqIWorkFormBaseService gxqWorkFormBaseService;
    @Autowired
    private GxqITworkFormLogService gxqITworkFormLogService;
    @Autowired
    private GxqIWfSendBackService gxqWfSendBackService;
    

    /**
     * 下级退回电话工单审核 退回审核页面
     *
     * @param
     * @return
     */
    @GetMapping("/treturnReason/{pkId}")
    public ModelAndView treturnReason(@PathVariable("pkId") Integer pkId, ModelMap map) {
        GxqTwfSendBackEty GxqTwfSendBackEty = gxqWfSendBackService.getById(pkId);
        GxqTworkFormBaseEty GxqTworkFormBaseEty = gxqWorkFormBaseService.getById(GxqTwfSendBackEty.getWfId());
        if (GxqTworkFormBaseEty !=null ) {
            map.put("workFormBase", GxqTworkFormBaseEty);
            map.put("sendBackEty",GxqTwfSendBackEty);
        }
        map.put("pkId",pkId);
        map.put("smsInform",smsNoteService.selectSmsInform(getSysUser().getDeptId().toString(), getSysUser().getUserId().toString()));
        return new ModelAndView(prefix + "/treturnReason");
    }

    /**
     * 下级退回电话工单审核 退回审核数据
     *
     * @return
     */
    @PostMapping("/treturnPassTwoBackJson")
    public AjaxResult treturnPassTwoBackJson(GxqTwfSendBackEty GxqTwfSendBackEty, HttpServletRequest req) {
        SysUser user = ShiroUtils.getSysUser();
        QueryWrapper<GxqTwfSendBackEty> queryWrapper = new QueryWrapper<>();
        //获取最新一轮的第一个派单
        queryWrapper.eq("wfId", GxqTwfSendBackEty.getWfId());
        queryWrapper.eq("sdeptId", "304");
        queryWrapper.notIn("sendState",30,40);
        queryWrapper.orderByDesc("pkId");
        queryWrapper.select("top 1 pkId,sendTime");
        List<GxqTwfSendBackEty> rootList = gxqWfSendBackService.list(queryWrapper);
        //当前部门下派的单子
        queryWrapper = new QueryWrapper<>();
        //条件isdel=0会自动加上
        queryWrapper.eq("wfId", GxqTwfSendBackEty.getWfId());
        queryWrapper.eq("sdeptId",user.getDeptId());
        queryWrapper.notIn("sendState",30,40);
        if(rootList != null && rootList.size() > 0) {
            queryWrapper.gt("sendTime",rootList.get(0).getSendTime());
        }
        queryWrapper.orderByDesc("pkId");
        List<GxqTwfSendBackEty> sendList2 = gxqWfSendBackService.list(queryWrapper);
//        List<GxqTwfSendBackEty> sendList3 = new ArrayList<>();
//        for(GxqTwfSendBackEty item : sendList2) {
//            //排除退回上级审核同意的单子
//            if(!(item.getSendState() == 40 && item.getBackState() == 21)) {
//                sendList3.add(item);
//            }
//        }
        if(sendList2 != null && sendList2.size() > 0) {
            AjaxResult ajaxResult = new AjaxResult();
            ajaxResult.put("msg", "当前部门下派了多个部门，不能再退");
            ajaxResult.put("code", "470");
            return ajaxResult;
        }
        boolean resultFlag = true;
//        treturnReasonJson(GxqTwfSendBackEty, req);
        treturnReasonJson(GxqTwfSendBackEty, "", req);
        //查询需设置为再退的单子
        queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("wfId", GxqTwfSendBackEty.getWfId());
        queryWrapper.eq("sbDeptId",user.getDeptId());
        queryWrapper.notIn("sendState",30,40,51);
        if(rootList != null && rootList.size() > 0) {
            queryWrapper.ge("sendTime",rootList.get(0).getSendTime());
        }
        queryWrapper.orderByDesc("pkId");
        List<GxqTwfSendBackEty> sendList = gxqWfSendBackService.list(queryWrapper);

        if(sendList != null && sendList.size() > 0) {
            //只取最新的一个派单，重复派单不管 设置为退回单
            GxqTwfSendBackEty sendBack = sendList.get(0);
            UpdateWrapper<GxqTwfSendBackEty> updateWrapper = new UpdateWrapper<>();
            updateWrapper.set("sendState", 40);
            updateWrapper.set("backState", 11);
            updateWrapper.set("flagInt", 1); //待审核
            updateWrapper.set("backRemark", GxqTwfSendBackEty.getBackRemark());
            updateWrapper.eq("pkId", sendBack.getPkId());
            gxqWfSendBackService.update(updateWrapper);
            //记录退回操作日志
            GxqTworkFormLogEty etyLog = new GxqTworkFormLogEty();
            etyLog.setWfId(GxqTwfSendBackEty.getWfId()); //[tWorkFormBase]PkId
            etyLog.setOpDeptNo(user.getDeptId().toString());
            etyLog.setOpDeptName(user.getDeptName());
            etyLog.setOpUserNo(user.getUserNo());
            etyLog.setOpUserName(user.getUserName());
            etyLog.setOpBtnId(-1);
            etyLog.setOpAction("退回");
            etyLog.setWsDesc("退回工单。"); //Show In website
            if ("21".equals(GxqTwfSendBackEty.getSortCode())) {
                etyLog.setWsOpen(0); //website ShowFlag
                etyLog.setEffectFlag(0);
            } else {
                etyLog.setWsOpen(1); //website ShowFlag
                etyLog.setEffectFlag(1);
            }
            //修改通过后在退回描述
            etyLog.setOpDesc("退回: " + GxqTwfSendBackEty.getSdeptName() + "（" + GxqTwfSendBackEty.getBackRemark() + "）");
            resultFlag = gxqITworkFormLogService.save(etyLog) > 0;
        }
        return toAjax(resultFlag);
    }

    /**
     * 下级退回电话工单审核 退回审核数据
     *
     * @return
     */
    @PostMapping("/treturnReasonJson")
    public AjaxResult treturnReasonJson(GxqTwfSendBackEty GxqTwfSendBackEty,String isOpenThis, HttpServletRequest req) {
        boolean resultFlag = true; boolean isSmsNote = false;//是否发送短信
        GxqTwfSendBackEty oldTwfSendBack = gxqWfSendBackService.getById(GxqTwfSendBackEty.getPkId());
        // 防止多次点击通过或不通过
        if(oldTwfSendBack != null && !(oldTwfSendBack.getBackState() == 21 || (oldTwfSendBack.getBackState() == 0 && oldTwfSendBack.getSendState() == 51))) {
            SysUser user = ShiroUtils.getSysUser();
            // 同意 状态为 backState=21 不同意状态为backState=22 ,特殊角色 不同意状态为 backState=0 sendState=51
            String temp = "";
            String opDesc = "";
            String reason = req.getParameter("txtReason");
            String opinion = GxqTwfSendBackEty.getSendRemark();
            if (reason.length() > 1) {
                temp = opinion + "（" + reason + "）";
            } else {
                temp = opinion;
            }
            UpdateWrapper<GxqTwfSendBackEty> updateWrapper = new UpdateWrapper<>();
            updateWrapper.set("FlagInt", 0);
            updateWrapper.eq("pkId", GxqTwfSendBackEty.getPkId());
            //通过并且修改工单状态 210,240 市政府办 市网络理政办  210,240,260,290,310,340
//            if (GxqTwfSendBackEty.getBackState() == 21 && !"210,240,260,290,310,340".contains(user.getRoles().get(0).getRoleId().toString())) {
            if (GxqTwfSendBackEty.getBackState() == 21) {
                //通过只修改派单状态
                opDesc = "通过";
                updateWrapper.set("BackState", 21);
                updateWrapper.set("sendRemark", temp);
                if(304 == user.getDeptId()) {
                    UpdateWrapper<GxqTworkFormBaseEty> wfUpdateWrapper = new UpdateWrapper<>();
                    wfUpdateWrapper
                            .set("WsUFlag", 1)
                            .set("CrtStepID", 401)
                            .set("CrtStepName", "市级" + GxqTwfSendBackEty.getSortName() + "退回")
                            .set("CrtStepTime", new Date())
                            .eq("PkId", GxqTwfSendBackEty.getWfId());
                    gxqWorkFormBaseService.update(wfUpdateWrapper);
                }
            }
            //不通过
            else {
                opDesc = "不通过";
                updateWrapper.set("BackState", 0);
                updateWrapper.set("SendState", 51);
                updateWrapper.set("SendRemark", temp);
                updateWrapper.set("GetTime", new Date());
                updateWrapper.set("GetPerson", user.getLoginName());
                updateWrapper.set("GetPerTel", user.getTklTNo());
                updateWrapper.set("BackRemark", "");
                //短信
                Integer smsInform = smsNoteService.selectSmsInform(user.getDeptId().toString(), user.getUserId().toString());
                if(smsInform != null && smsInform == 1){//11
                    if (isOpenThis != null && isOpenThis.equals("1")) {
                        isSmsNote = true;
                    }
                }else{//01
                    if (isOpenThis != null && isOpenThis.equals("1")) {
                        isSmsNote = true;
                    }
                }

            }
            //新增工单操作日志
            opDesc = GxqTwfSendBackEty.getSbdeptName() + "退回工单审核（" + opDesc + "）";
            GxqTworkFormLogEty etyLog = new GxqTworkFormLogEty();
            etyLog.setWfId(GxqTwfSendBackEty.getWfId()); //from URL //2014-4-5
            etyLog.setOpDeptNo(user.getDeptId().toString());
            etyLog.setOpDeptName(user.getDeptName());
            etyLog.setOpUserNo(user.getUserNo());
            etyLog.setOpUserName(user.getUserName());
            etyLog.setOpAction("审核退回工单");
            etyLog.setOpBtnId(-1);
            etyLog.setWsDesc(opDesc); //Show In website
            etyLog.setWsOpen(GxqTwfSendBackEty.getBackState() == 21 ? 1 : 0); //website ShowFlag
            etyLog.setOpDesc(opDesc);
            etyLog.setEffectFlag(GxqTwfSendBackEty.getBackState() == 21 ? 1 : -1);
            gxqITworkFormLogService.save(etyLog);
            resultFlag = gxqWfSendBackService.update(updateWrapper);
            //更新父级派单状态
            commonDao.proTsubBackState(GxqTwfSendBackEty.getWfId(),GxqTwfSendBackEty.getPkId());
            //发送短信
            if(isSmsNote){
                smsNoteService.sendSmsNote(oldTwfSendBack.getSbdeptId(),GxqTwfSendBackEty.getMyTwfNO(),"退回");
            }
        }
        return toAjax(resultFlag);
    }

    /**
     * 回访意见列表数据
     *
     * @param wfId
     * @return
     */
    @RequestMapping("/judgeList/{wfId}")
    public TableDataInfo simulacrumList(@PathVariable("wfId") Integer wfId) {
        startPage();
        List<Map<String, Object>> list = gxqITwfJudgeService.selectByWfId(wfId);
        return getDataTable(list);
    }

    /**
     * 回访意见 详情页面
     *
     * @param pkId
     * @param map
     * @return
     */
    @GetMapping("/JudgeDetail/{pkId}")
    public ModelAndView JudgeDetail(@PathVariable("pkId") Integer pkId, ModelMap map) {
        GxqTwfJudgeEty twfJudgeEty = gxqITwfJudgeService.getById(pkId);
        map.put("twfJudge", twfJudgeEty);
        return new ModelAndView(prefix + "/JudgeDetail");
    }

    /**
     * 进入派单办理情况详情页面
     * @param sbId 派单id
     * @param map 模型对象
     * @return 视图
     */
    @GetMapping("/dealDetail/{sbId}")
    public ModelAndView dealDetail(@PathVariable("sbId") Integer sbId, ModelMap map) {
        map.put("sendBackEty",gxqWfSendBackService.getById(sbId));
        return new ModelAndView(prefix+"/dealDetail");
    }

    /**
     * 派单情况记录列表页面
     *
     * @param wfId 工单编号
     * @param map 模型对象
     * @return 视图对象
     */
    @GetMapping("/dealList/{wfId}")
    public ModelAndView dealList(@PathVariable("wfId") Integer wfId,Integer sbId,ModelMap map) {
        map.put("wfId",wfId);
        map.put("sbId",sbId);
        map.put("deptName",getSysUser().getDeptName());
        return new ModelAndView(prefix+"/dealList");
    }

    /**
     * 派单情况列表数据
     *
     * @return 列表数据
     */
    @PostMapping("/dealListJson/{wfId}")
    public TableDataInfo dealListJson(@PathVariable("wfId") Integer wfId) {
        startPage();
        List<GxqTwfSendBackEty> list = gxqWfSendBackService.dealListJson(wfId);
        return getDataTable(list);
    }


    /**
     * 历史处理记录 列表页面
     *
     * @param map
     * @return
     */
//    @GetMapping("/logList/{wfId}")
//    public ModelAndView logList(@PathVariable("wfId") Integer wfId,ModelMap map) {
//        map.put("wfId",wfId);
//        return new ModelAndView(prefix+"/logList");
//    }

    /**
     * 历史处理记录 列表数据
     *
     * @return
     */
    @PostMapping("/logListJson/{wfId}")
    public TableDataInfo logListJson(@PathVariable("wfId")Integer wfId) {
        startPage();
        List<GxqTworkFormLogEty> list = gxqITworkFormLogService.logListJson(wfId);
        return getDataTable(list);
    }


    /**
     * 进入历史处理记录详情页面
     * @param logId 日志id
     * @param map 模型对象
     * @return 视图
     */
    @GetMapping("/logDetail/{logId}")
    public ModelAndView logDetail(@PathVariable("logId") Integer logId, ModelMap map) {
        map.put("logEty",gxqITworkFormLogService.selectById(logId));
        return new ModelAndView(prefix+"/logDetail");
    }

    /**
     * 日志切换公开状态
     *
     * @return
     */
    @PostMapping("/updateState/{logId}")
    public AjaxResult updateState(@PathVariable("logId")Integer logId) {
        return toAjax(gxqITworkFormLogService.updateState(logId));
    }

    /**
     * 打印转办单
     * @param ids 派单编号
     * @return 页面
     */
    @GetMapping("/printSends")
    public ModelAndView printSends(String ids){
        SysUser user = getSysUser();
        ModelAndView mav = new ModelAndView(prefix+"/printSends");
        String[] idList = ids.split(",");
        List<GxqTwfSendBackEty> list = new ArrayList<>();
        for (String id : idList) {
            GxqTwfSendBackEty send = gxqWfSendBackService.getById(Integer.parseInt(id));
            GxqTworkFormBaseEty GxqTworkFormBaseEty = gxqWorkFormBaseService.getById(send.getWfId());
            commonController.hidetTel_gxq(user,GxqTworkFormBaseEty);
            send.setTworkFormEty(GxqTworkFormBaseEty);
            list.add(send);
        }
        mav.addObject("sends",list);
        return mav;
    }
}
